<?php

namespace Acme\BaseBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie; 

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('AcmeBaseBundle:Default:index.html.twig', array('name' => $name));
    }
    
    
    /**
     * setSession
     * 
     * @param type $name string
     * @param type $value string 
     * @param type $expire int
     * 
     * return
     */
    public function setSession($name, $value, $expire)
    {
        
    }
    
    /**
     * getSession
     * 
     * @param type $name string
     * 
     * return
     */
    public function getSession($name)
    {
        
    }
    
    /**
     * clearSession
     * 
     * 
     * return
     */    
    public function clearSession() 
    {

    }
    
    /**
     * setCookie
     * 
     * @param type $name string
     * @param type $value string 
     * @param type $expire int
     * 
     * return
     */   
    public function setCookie($name, $value, $expire = 0)
    {
        $response = new Response();
        $response->headers->setCookie(new Cookie($name, $value, time() + $expire));
        $response->send();
    }

    /**
     * getCookie
     * 
     * @param type $name string
     * 
     * return
     */
    public function getCookie($name)
    {
        $request = $this->getRequest();
        $Cookie = $request->cookies->all();
/*
$search_array = array('first' => null, 'second' => 4);
// returns false
isset($search_array['first']);
// returns true
array_key_exists('first', $search_array);
 */
        return $request->cookies->has($name) ? $Cookie[$name] : null;
    }
    
    /**
     * clearCookie
     * 
     * 
     * return
     */
    public function clearCookie() 
    {
        $response = new Response();
        $Cookie = $request->cookies->all();
        foreach($Cookie as $name=>$value) {
            $response->headers->setCookie(new Cookie($name, $value, -1));
        }
        
        $response->send();
    }
    
    /**
     * clear session and cookie
     * 
     * 
     * return
     */
    public function clearAll()
    {
        $this->clearCookie();
        $this->clearSession();
    }
    
    /**
     * random
     * 
     * @param type $type string mixed是英文字符和数字，number是纯数字
     * @param type $length 字符长度
     * 
     * return
     */
    public function generateSalt($length = 6, $type = 'mixed') 
    {
        // 密码字符集，可任意添加你需要的字符
        if ($type === 'mixed') {
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        } else if ($type === 'number') {
            $chars = '0123456789';
        } else {}
        
        $salt = '';
        for ($i = 0; $i < $length; $i++) {
            $salt .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        
        return $salt;
    }
}    

